import os.path
import uuid
import hashlib

import os
from django.shortcuts import render
from django.conf import settings
#
from apps.student.models import Student
# Create your views here.
#
from django.http import JsonResponse
import json
from django.db.models import Q


def get_students(request):
    try:
        # 获取所有学生的信息
        obj_students = Student.objects.all().values()
        # 把结果转换为list
        students = list(obj_students)
        # 返回
        return JsonResponse({'code': 1, 'data': students})
    except Exception as e:
        # 如果出现异常 返回
        return JsonResponse({'code': 0, 'msg': '获取学生信息出现异常,具体错误' + str(e)})


def query_students(request):
    data = json.loads(request.body.decode('utf-8'))
    try:
        # 获取所有学生的信息
        obj_students = Student.objects.filter(Q(sno__icontains=data['inputstr']) | Q(name__icontains=data['inputstr']) |
                                              Q(gender__icontains=data['inputstr']) | Q(mobile__icontains=data['inputstr'])
                                              | Q(email__icontains=data['inputstr']) | Q(address__icontains=data['inputstr'])
                                              ).values()
        # 把结果转换为list
        students = list(obj_students)
        # 返回
        return JsonResponse({'code': 1, 'data': students})
    except Exception as e:
        # 如果出现异常 返回
        return JsonResponse({'code': 0, 'msg': '查询学生信息出现异常,具体错误' + str(e)})


def is_exsits_sno(request):
    data = json.loads(request.body.decode('utf-8'))
    try:
        obj_students = Student.objects.filter(sno=data['sno'])
        if obj_students.count() == 0:
            return JsonResponse({'code': 1, 'exists': False})
        else:
            return JsonResponse({'code': 1, 'exists': True})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': '效验学号失败，具体原因：' + str(e)})


def add_student(request):
    # 添加学生到数据库
    # 接收前端传递过来的数据
    data = json.loads(request.body.decode('utf-8'))
    # 添加到数据库
    try:
        obj_student = Student(sno=data['sno'], name=data['name'], gender=data['gender'],
                                birthday=data['birthday'], mobile=data['mobile'],
                              email=data['email'], address=data['address'], image=data['image'])
        # 执行添加
        obj_student.save()
        #
        obj_student = Student.objects.all().values()
        students = list(obj_student)

        return JsonResponse({'code': 1, 'data': students})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': '添加到数据库出现异常具体原因' + str(e)})


def update_student(request):
    # 修改学生到数据库
    # 接收前端传递过来的数据
    data = json.loads(request.body.decode('utf-8'))
    try:
        #
        obj_student = Student.objects.get(sno=data['sno'])
        obj_student.name = data['name']
        obj_student.gender = data['gender']
        obj_student.birthday = data['birthday']
        obj_student.mobile = data['mobile']
        obj_student.email = data['email']
        obj_student.address = data['address']
        obj_student.image = data['image']
        obj_student.save()
        #
        obj_student = Student.objects.all().values()
        students = list(obj_student)

        return JsonResponse({'code': 1, 'data': students})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': '修改保存到数据库出现异常具体原因' + str(e)})


def delete_student(request):
    data = json.loads(request.body.decode('utf-8'))
    try:
        #
        obj_student = Student.objects.get(sno=data['sno'])
        obj_student.delete()
        #
        obj_student = Student.objects.all().values()
        students = list(obj_student)

        return JsonResponse({'code': 1, 'data': students})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': '删除学生信息数据库出现异常具体原因' + str(e)})


def delete_students(request):
    date = json.loads(request.body.decode('utf-8'))
    try:
        for one_student in date['student']:
            obj_student = Student.objects.get(sno=one_student['sno'])
            obj_student.delete()
        obj_student = Student.objects.all().values()
        students = list(obj_student)

        return JsonResponse({'code': 1, 'data': 'students'})
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': '批量删除学生信息数据库出现异常具体原因' + str(e)})


def upload(request):
    # 上传文件
    rev_file = request.FILES.get('avatar')
    if not rev_file:
        return JsonResponse({'code': 0, 'msg': '图片不存在'})

    new_name = get_random_str()
    file_path = os.path.join(settings.MEDIA_ROOT, new_name + os.path.splitext(rev_file.name)[1])
    try:
        f = open(file_path, 'wb')
        for i in rev_file.chunks():
            f.write(i)
        f.close()

        return JsonResponse({'code': 1, 'name': new_name + os.path.splitext(rev_file.name)[1]})

    except Exception as e:
        return JsonResponse({'code': 0, 'msg': str(e)})


def get_random_str():
    uuid_val = uuid.uuid4()
    uuid_str = str(uuid_val).encode('utf-8')
    md5 = hashlib.md5()
    md5.update(uuid_str)
    return md5.hexdigest()
